package com.hfi.ood.litejunit.v3.framework.request;

import com.hfi.ood.litejunit.v3.framework.annotation.RunWith;
import com.hfi.ood.litejunit.v3.framework.runner.Runner;
import com.hfi.ood.litejunit.v3.framework.runners.TestClassRunner;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author ChangLiang
 * @date 2020/5/28
 */
public class ClassRequest extends Request {

    private final Class<?> fTestClass;

    public ClassRequest(Class<?> each) {
        this.fTestClass = each;
    }

    @Override
    public Runner getRunner() {
        // Suite
        Class runnerClass = getRunnerClass(fTestClass);
        try {
            Constructor constructor = runnerClass.getConstructor(Class.class);
            Runner runner = (Runner) constructor.newInstance(new Object[]{fTestClass});
            return runner;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Class getRunnerClass(Class<?> testClass) {
        RunWith annotation = testClass.getAnnotation(RunWith.class);
        if (annotation != null) {
            return annotation.value();
        } else {
            return TestClassRunner.class;
        }
    }
}
